package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.FriendApply;
import org.aeon.entity.User;
import org.aeon.entity.UserRelation;
import org.aeon.entity.dto.FriendApplyDto;
import org.aeon.message.request.FriendAddRequestMessage;
import org.aeon.message.response.FriendAddResponseMessage;
import org.aeon.message.response.IllegalRequestResponseMessage;
import org.aeon.service.FriendApplyService;
import org.aeon.service.UserRelationService;
import org.aeon.service.factory.FriendApplyServiceFactory;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;
import org.modelmapper.ModelMapper;

import java.util.Set;

/**
 * @author: MissingAeon
 * @date: 2024/1/27 17:07
 * @description: 好友添加请求消息处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class FriendAddRequestHandler extends SimpleChannelInboundHandler<FriendAddRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FriendAddRequestMessage msg) throws Exception {
        final FriendAddResponseMessage resMsg = new FriendAddResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final FriendApply friendApply = new ModelMapper().map(msg.getFriendApply(), FriendApply.class);

        // 检查合法
        if (check(ctx, msg)) ctx.writeAndFlush(new IllegalRequestResponseMessage());

        // 获取来源
        final User user = UserServiceFactory.getService().getUserById(friendApply.getUserId());
        final Byte agree = friendApply.getAgree();
        if (user == null) {
            // 不存在，失败并忽略
            FriendApplyServiceFactory.getService().updateFriendApplyResult(friendApply);
            resMsg.setResponse(false, "对方用户已注销");
        } else if (agree == 3) {
            // 忽略
            FriendApplyServiceFactory.getService().updateFriendApplyResult(friendApply);
            resMsg.setResponse(true, "好友添加已忽略");
        } else if (agree == 2) {
            // 拒绝
            FriendApplyServiceFactory.getService().updateFriendApplyResult(friendApply);
            resMsg.setResponse(true, "好友添加已拒绝");
        } else if (agree == 1) {
            // 添加好友
            final UserRelationService relationService = UserRelationServiceFactory.getService();
            final UserRelation userRelation = relationService.queryRelation(user.getId(), friendApply.getAnotherUserId());
            if (userRelation != null) {
                resMsg.setResponse(false, "重复添加");
                ctx.writeAndFlush(resMsg);
            } else {
                relationService.addFriends(friendApply);
                resMsg.setResponse(true, "好友添加成功");
            }
        }
        ctx.writeAndFlush(resMsg);
    }


    /**
     * 检查
     * 首先getAgree不为0
     * 有申请记录
     * 消息发起人为被申请人
     *
     * @param ctx
     * @param msg
     * @return
     */
    private boolean check(ChannelHandlerContext ctx, FriendAddRequestMessage msg) {
        // 确认是队列中的消息
        final FriendApplyService service = FriendApplyServiceFactory.getService();
        final FriendApplyDto friendApply = msg.getFriendApply();
        if (!Set.of(1, 2, 3).contains((int) friendApply.getAgree())) {
            return false;
        }
        if (service.isApplyExist(friendApply.getUserId(), friendApply.getAnotherUserId())) {
            final Long userId = SessionFactory.getSession().getUserId(ctx.channel());
            return userId.equals(friendApply.getAnotherUserId());
        }
        return false;
    }
}
